package com.lzy.system.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.conf.I18nServiceImpl;
import com.lzy.exception.BusException;
import com.lzy.system.organization.dto.SysCompanyDTO;
import com.lzy.system.organization.entity.SysCompany;
import com.lzy.system.organization.entity.security.entity.SecurityUser;
import com.lzy.system.organization.mapper.SysCompanyMapper;
import com.lzy.system.organization.service.ISysCompanyService;
import com.lzy.system.organization.service.ISysUserMappingService;
import com.lzy.utils.BeanMapHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * description:  公司信息管理<br>
 * date: 2023/11/12 下午10:47 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
@Service
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements ISysCompanyService {
    ISysUserMappingService iSysUserMappingService;
    I18nServiceImpl i18nService;

    @Autowired
    public SysCompanyServiceImpl(ISysUserMappingService iSysUserMappingService, I18nServiceImpl i18nService) {
        this.iSysUserMappingService = iSysUserMappingService;
        this.i18nService = i18nService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCompany(List<SysCompanyDTO> sysCompanyDTOList) throws BusException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
        String userId = securityUser.getUsername();
        List<SysCompany> sysCompanies = new ArrayList<>();
        for (SysCompanyDTO sysCompanyDTO : sysCompanyDTOList) {
            //检测公司编号是否存在
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_no",sysCompanyDTO.getCompany_no());
            queryWrapper.select("id");
            SysCompany one = this.getOne(queryWrapper);
            if(one != null){
                throw new BusException(i18nService.getMessage("system.org.company.exists"));
            }
            SysCompany sysCompany = (SysCompany)BeanMapHelper.Bean2Bean(sysCompanyDTO,SysCompany.class);
            sysCompany.setCreate_userid(userId);
            sysCompany.setCreate_date(new Date());
            sysCompany.setOrderindex(0);
            sysCompanies.add(sysCompany);
        }
        boolean update = this.saveBatch(sysCompanies);
        if(!update){
            throw new BusException(i18nService.getMessage("system.org.company.add.fail"));
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompany(List<SysCompanyDTO> sysCompanyDTOList) throws BusException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
        String userId = securityUser.getUsername();
        List<SysCompany> sysCompanies = new ArrayList<>();
        for (SysCompanyDTO sysCompanyDTO : sysCompanyDTOList) {
            //检测公司编号是否存在 排除自己
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("company_no",sysCompanyDTO.getCompany_no());
            queryWrapper.ne("id",sysCompanyDTO.getId());
            queryWrapper.select("id");
            SysCompany one = this.getOne(queryWrapper);
            if(one != null){
                throw new BusException(i18nService.getMessage("system.org.company.exists")+"["+sysCompanyDTO.getCompany_no()+"]");
            }
            SysCompany sysCompany = (SysCompany)BeanMapHelper.Bean2Bean(sysCompanyDTO,SysCompany.class);
            sysCompany.setUpdate_date(new Date());
            sysCompany.setUpdate_userid(userId);
            sysCompanies.add(sysCompany);
        }
        boolean update = this.updateBatchById(sysCompanies);
        if(!update){
            throw new BusException(i18nService.getMessage("system.org.company.update.fail"));
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delById(String ids) throws BusException {
        ArrayList<Integer> ids_arr = new ArrayList<>();
        for (int i : StrUtil.splitToInt(ids, ",")) {
            ids_arr.add(i);
        }
        boolean remove = this.removeBatchByIds(ids_arr);
        if(!remove){
            throw new BusException(i18nService.getMessage("system.org.company.del.fail"));
        }
        return remove;
    }

    @Override
    public IPage<SysCompany> getCompanyList(String company_name, String company_no, int limit, int page) throws BusException {
        Page<SysCompany> Ipage = new Page<>(page,limit);
        QueryWrapper<SysCompany> queryWrapper = new QueryWrapper();
        if(!StrUtil.isBlank(company_name)){
            queryWrapper.like("company_name",company_name);
            queryWrapper.or();
        }
        if(!StrUtil.isBlank(company_name)){
            queryWrapper.like("company_name",company_name);
            queryWrapper.or();
        }
        queryWrapper.orderByDesc("is_def");
        queryWrapper.orderByAsc("orderindex","create_date");
        IPage res = this.page(Ipage, queryWrapper);
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDef(int id) throws BusException {
        //取消全部默认值
        update(new SysCompany(){{
            setIs_def(0);
        }},new QueryWrapper(){{
            eq("is_def",1);
        }});

        //设置当前id 默认
        updateById(new SysCompany(){{
            setId(id);
            setIs_def(1);
        }});
        return true;
    }
}
